package com.baibei.ebec.home.index;


import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baibei.ebec.home.R;
import com.baibei.ebec.home.R2;
import com.baibei.ebec.home.index.holder.JewelryTypeViewHolder;
import com.baibei.ebec.home.index.holder.ShipmentProductViewHolder;
import com.baibei.ebec.sdk.ApiConstant;
import com.baibei.ebec.sdk.BuildConfig;
import com.baibei.ebec.sdk.TokenInfo;
import com.baibei.ebec.totrade.ToTradeFragment;
import com.baibei.ebec.web.CampaignActivity;
import com.baibei.model.Area;
import com.baibei.model.BannerInfo;
import com.baibei.model.CouponInfo;
import com.baibei.model.LastPriceInfo;
import com.baibei.model.ProductInfo;
import com.baibei.model.QuotationInfo;
import com.baibei.model.RankingInfo;
import com.baibei.model.ShipmentInfo;
import com.baibei.model.TradeType;
import com.baibei.model.UserInfo;
import com.baibei.model.event.LoginEvent;
import com.baibei.module.AppRouter;
import com.baibei.module.BasicActivity;
import com.baibei.module.BasicFragment;
import com.baibei.module.RechargeHelper;
import com.baibei.sdk.ApiCode;
import com.baibei.sdk.ApiException;
import com.baibei.sdk.TokenEvent;
import com.baibei.ui.AppUI;
import com.baibei.widget.CommonRefreshLayout;
import com.baibei.widget.Toolbar;
import com.blankj.utilcode.utils.LogUtils;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.rae.swift.Rx;
import com.rae.swift.session.SessionManager;
import com.rae.widget.dialog.DialogBuilder;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONObject;

import java.io.Console;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static com.baibei.sdk.OkHttpUtils.logRequest;
import static com.umeng.socialize.utils.ContextUtil.getPackageName;

/**
 * 首页碎片
 */
public class HomeIndexFragment extends BasicFragment implements HomeIndexContract.View, JewelryTypeViewHolder.OnAreaListener,
        ShipmentProductViewHolder.OnProductClickListener, HomeIndexAdapter.OnBannerClickListener, View.OnTouchListener {

    @BindView(R2.id.toolbar)
    Toolbar mToolbar;
    @BindView(R2.id.recyclerView)
    RecyclerView mRecyclerView;
    @BindView(R2.id.refresh_layout)
    CommonRefreshLayout mRefreshLayout;

    @BindView(R2.id.tv_recharge)
    View mRechargeView;

    @BindView(R2.id.tv_customer_service)
    View mServiceQQ;

    Unbinder unbinder;
    @BindView(R2.id.iv_pop)
    ImageView ivPop;

    private HomeIndexAdapter mAdapter;
    private HomeIndexContract.Presenter mPresenter;
    private List<HomeIndexAdapterModel> mDataModels = new ArrayList<>(); // 适配器数据源
    private HomeIndexAdapterModel mBannerModel = new HomeIndexAdapterModel(HomeIndexAdapterModel.VIEW_TYPE_BANNER); // 广告数据
    private boolean mIsFromRecharge;
    private String mDeviceId;
    private int lastX;
    private int lastY;
    private boolean isClick;
    private long startTime;
    private long endTime;
    private int height;
    private int deltaX;
    private int deltaY;
    private List<ShipmentInfo> mDataList;
    private List<LastPriceInfo> mLastPriceInfoList;
    private ToTradeFragment toTradeFragment;

    public HomeIndexFragment() {
    }

    public static HomeIndexFragment newInstance() {
        return newInstance(Area.ALL);
    }

    public static HomeIndexFragment newInstance(Area area) {
        HomeIndexFragment fm = new HomeIndexFragment();
        Bundle args = new Bundle();
        args.putString("area", area.name());
        fm.setArguments(args);
        return fm;
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        mPresenter = inject(HomeIndexContract.Presenter.class);
    }
    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Subscribe
    public void onEvent(LoginEvent event) {
        //重新刷新界面
        if (isAdded()) {
            mRefreshLayout.autoRefresh();
        }
    }


    @Override
    public int getLayoutId(Bundle bundle) {
        return R.layout.fragment_index;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        mDataModels.clear(); // 清除数据
        mToolbar.setTitle(getString(R.string.title_home_index));
        mToolbar.hideHomeAsUp();
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mRecyclerView.getItemAnimator().setChangeDuration(0);
        mAdapter = new HomeIndexAdapter(getArea() != Area.ALL);
        mAdapter.setAreaListener(this);
        mAdapter.setOnProductClickListener(this);
        mAdapter.setOnBannerClickListener(this);
        mDataModels.add(new HomeIndexAdapterModel(HomeIndexAdapterModel.VIEW_TYPE_AREA));
        mRecyclerView.setAdapter(mAdapter);

        mRefreshLayout.disableWhenHorizontalMove(true);
        mRefreshLayout.setPtrHandler(new PtrDefaultHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout ptrFrameLayout) {
                mPresenter.start();
            }
        });

        WindowManager wm = getActivity().getWindowManager();
        height = wm.getDefaultDisplay().getHeight();
        ivPop.setOnTouchListener(this);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mPresenter.start();
    }

    @Override
    public void onResume() {
        super.onResume();
        mPresenter.loadBalanceAndCoupons();
        mPresenter.loadlastprice();
        if (SessionManager.getDefault().isLogin()) {
            UserInfo user = SessionManager.getDefault().getUser();
            if (user.getUserType() == UserInfo.USER_TYPE_ENTERPRISE) {
                // 企业会员
                mRechargeView.setVisibility(View.GONE);
                mServiceQQ.setVisibility(View.GONE);
            } else {
                mRechargeView.setVisibility(View.VISIBLE);
                mServiceQQ.setVisibility(View.VISIBLE);
            }
        } else {
            mRechargeView.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onAreaClickListener(Area area) {
        AppRouter.routeToAreaList(getContext(), area);
    }

    @Override
    public void onLoadBannerData(List<BannerInfo> data) {
        mDataModels.remove(mBannerModel);
        mDataModels.add(0, mBannerModel);
        mBannerModel.setBanners(data);
        mAdapter.setDataList(mDataModels);
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onLoadClosePrice(List<LastPriceInfo> data) {
        mLastPriceInfoList=data;
    }


    @Override
    public ProductInfo getProduct() {
        return mDataList.get(0).getProducts().get(0);
    }


    @Override
    public void onEmptyBanner() {
        mDataModels.remove(mBannerModel);
        mAdapter.setDataList(mDataModels);
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onLoadComplete() {
        if (mRefreshLayout == null) return;
        mRefreshLayout.refreshComplete();
    }

    /**
     * 通过加载排行榜接口加载每个商品关市价
     */
    @Override
    public void onLoadCloseprice(List<RankingInfo> info) {

    }

    @Override
    public void refreshCompleted() {
        if (mRefreshLayout != null && mRefreshLayout.isRefreshing()) {
            mRefreshLayout.refreshComplete();
        }
    }

    @Override
    public Area getArea() {
        return Area.typeOf(getArguments().getString("area"));
    }

    @Override
    public void onLoadBannerFailed(String s) {
        if (getContext() == null) return;
        AppUI.failed(getContext(), s);
    }

    @Override
    public void onLoadServiceQQSuccess(String url) {
        try {
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
        } catch (Exception e) {
            new DialogBuilder(getContext())
                    .setMessage("启动QQ失败，QQ号码已经复制，请前往QQ添加我们的客服QQ。")
                    .negativeButtonHidden()
                    .show();
        }
    }

    /**
     * 判断qq是否可用
     */
    public boolean isQQClientAvailable(Context context) {
        final PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals("com.tencent.mobileqq")) {
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public void onLoadServiceQQFailed(String msg) {
        AppUI.failed(getContext(), msg);
    }

    @Override
    public void hideLoading() {
        AppUI.dismiss();
    }

    @Override
    public void showLoading() {
        AppUI.loading(getContext());
    }

//    @Override
//    public void onLoadCoupons(List<CouponInfo> couponInfos) {
//
//    }

    @Override
    public void onNoMoreData() {

    }

    @Override
    public void onEmptyData(String s) {
        onLoadComplete();
        removeShipmentData();
        mAdapter.notifyDataSetChanged();
    }

    /**
     * 移除所有的船信息，以及产品信息
     */
    private void removeShipmentData() {
        int size = mDataModels.size();
        List<HomeIndexAdapterModel> temp = new ArrayList<>();
        for (int i = 0; i < size; i++) {
            HomeIndexAdapterModel item = mDataModels.get(i);
            if (item.getViewType() == HomeIndexAdapterModel.VIEW_TYPE_SHIPMENT_HEADER
                    || item.getViewType() == HomeIndexAdapterModel.VIEW_TYPE_SHIPMENT_PRODUCT) {
                temp.add(item);
            }
        }
        mDataModels.removeAll(temp);
    }


    public void notifychange(){
        if (toTradeFragment!=null){
            toTradeFragment.notifychange(mDataList.get(1).getProducts());
        }
    }
    @Override
    public void onLoadData(List<ShipmentInfo> list) {
        mDataList=list;
        // 移除数据
        notifychange();
        removeShipmentData();
        // 组合类型
        for (ShipmentInfo shipmentInfo : list) {
            HomeIndexAdapterModel shipmentModel = new HomeIndexAdapterModel(HomeIndexAdapterModel.VIEW_TYPE_SHIPMENT_HEADER);
            shipmentModel.setShipmentInfo(shipmentInfo);
            mDataModels.add(shipmentModel);
            int index = mDataModels.size() - 1;

            for (ProductInfo productInfo : shipmentInfo.getProducts()) {
                HomeIndexAdapterModel productModel = new HomeIndexAdapterModel(HomeIndexAdapterModel.VIEW_TYPE_SHIPMENT_PRODUCT);
                productModel.setShipmentIndex(index);
                productModel.setProductInfo(productInfo);
                mDataModels.add(productModel);
            }
        }
        mAdapter.setDataList(mDataModels);
        if (!Rx.isEmpty(list)) {
            //刷新视图，不刷新头部
            mAdapter.notifyItemRangeChanged(2, mAdapter.getItemCount() - 2);
        }
    }

    @Override
    public void onLoginExpired() {

    }

    @Override
    public void onPause() {
        super.onPause();
//        dialog.dismiss();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mAdapter.setOnProductClickListener(null);
        mAdapter.setAreaListener(null);
        if (unbinder != null) {
            unbinder.unbind();
        }
    }

    /**
     * 客服
     */
    @OnClick(R2.id.tv_customer_service)
    public void onCustomerClick() {

        final Dialog dialog = new Dialog(getContext(), 0);
        View view = LayoutInflater.from(getContext()).inflate(R.layout.layout_customer_service, null);
        TextView cuPhone = view.findViewById(R.id.tv_cuPhone);
        TextView cuQQ = view.findViewById(R.id.tv_cuQQ);
        cuPhone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                if (SessionManager.getDefault().isLogin()) {
                    Intent dialIntent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:4000925288"));
                    startActivity(dialIntent);
//                } else {
//                    AppRouter.routeToLogin(getActivity());
//                }
                dialog.dismiss();
            }
        });
        cuQQ.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //跳转qq
//                if (SessionManager.getDefault().isLogin()) {
                    if (!isQQClientAvailable(getContext())) {
                        new DialogBuilder(getContext()).negativeButtonHidden().setMessage("您的设备还未安装QQ客户端，不能进行临时会话！").show();
                        dialog.dismiss();
                        return;
                    }
                    mPresenter.getServiceQQ();
//                } else {
//                    AppRouter.routeToLogin(getActivity());
//                }
            }
        });
        dialog.setContentView(view);
        Window window = dialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        WindowManager.LayoutParams attributes = window.getAttributes();
        attributes.y = 20;
        window.setAttributes(attributes);
        dialog.show();
    }

    @OnClick(R2.id.tv_recharge)
    public void onRechargeClickListener() {
        //充值
        RechargeHelper.toRecharge(getActivity(), this);
        //test
        onUmengEvent("充值");
    }

    @Override
    public void onProductTradeClick(ShipmentInfo shipmentInfo, ProductInfo productInfo) {
        if (shipmentInfo == null) {

            return;
        }
        if (productInfo == null) {
            AppUI.failed(getContext(), "产品信息不存在");
            return;
        }
//        AppRouter.routeToTrade(getContext(), shipmentInfo.getEstimateTime(), productInfo, shipmentInfo.getSaleTips());
        if (mLastPriceInfoList==null)return;
        productInfo.setClosePrice(mLastPriceInfoList.get(1).getClosePrice());
        toTradeFragment = ToTradeFragment.newInstance(mDataList.get(1).getProducts(),productInfo, TradeType.BUY, mPresenter.getValidCouponList(), mPresenter.getSuggestNumbers(), mPresenter.getMaxDefindCount());
        toTradeFragment.show(getFragmentManager(),"totrade");
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == AppRouter.REQ_LOGIN && resultCode == Activity.RESULT_OK && mIsFromRecharge) {
            mIsFromRecharge = false;
            RechargeHelper.toRecharge(getActivity(), this);
        }
    }

    @Override
    public void onBannerClickListener(BannerInfo bannerInfo) {
        //跳转到网页操作
        if (TextUtils.isEmpty(bannerInfo.getJumpUrl())) {
            return;
        }
        if ("Nojump".equals(bannerInfo.getJumpUrl())){
            return;
        }
        if (!SessionManager.getDefault().isLogin()){
            AppRouter.routeToLogin(getActivity());
            return;
        }
        AppRouter.routeToWeb(getContext(), bannerInfo.getTitle(), bannerInfo.getJumpUrl());
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
//        unbinder1 = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @OnClick(R2.id.iv_pop)
    public void onViewClicked() {
//        popDialog();
    }

    private String getDeviceId() {
        mDeviceId = "BB-" + System.currentTimeMillis() + "-" + UUID.randomUUID().toString();
        return mDeviceId;
    }

    private String getVersion() {
        try {
            return getContext().getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_META_DATA).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return "1.0.0";
        }
    }

    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {

        int startX = (int)ivPop.getX();
        int startY = (int) ivPop.getY();
        int action = motionEvent.getAction();
        switch (action){
            case MotionEvent.ACTION_DOWN:
                isClick = false;
                lastX = (int)motionEvent.getRawX();
                lastY = (int)motionEvent.getRawY();
                startTime = System.currentTimeMillis();
                break;
            case MotionEvent.ACTION_MOVE:
                isClick = true;
                int currentX = (int)motionEvent.getRawX();
                Log.i("currentX",""+currentX);
                int currentY = (int)motionEvent.getRawY();
                Log.i("currentY",""+currentY);

                deltaX = currentX - lastX;
                deltaY = currentY - lastY;

                lastX = currentX;
                lastY = currentY;

                ivPop.setX(startX+ deltaX);

                if ((startY+ deltaY)>(height-dip2px(getContext(),54))){
                    ivPop.setY(height-dip2px(getContext(),100));
                } else if ((startY+ deltaY)<dip2px(getContext(),28)){
                    ivPop.setY(dip2px(getContext(),13));
                } else {
                    ivPop.setY(startY+ deltaY);
                }
//                ivPop.setY(startY+deltaY);
                break;
            case MotionEvent.ACTION_UP:
                endTime = System.currentTimeMillis();
                if ((endTime - startTime)>0.2*1000l){
                    isClick = true;
                } else {
                    isClick = false;
                }
                ivPop.setX(0);
                if ((startY+ deltaY)>(height-dip2px(getContext(),100))){
                    ivPop.setY(height-dip2px(getContext(),100));
                } else if ((startY+ deltaY)<dip2px(getContext(),28)){
                    ivPop.setY(dip2px(getContext(),13));
                } else {
                    ivPop.setY(startY+ deltaY);
                }
        }
        return isClick;
    }

    public static int dip2px(Context context, float dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }
}
